package com.we.flink.accountproxyuserlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.accountproxyuserlabelplatform.table.TableUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagUser {
    public long account_user_key;
    public String user_key;
    public int update_time;

    public static Logger LOG = LoggerFactory.getLogger(TagUser.class);

    public TagUser(long account_user_key, String user_key, int update_time) {
        this.account_user_key = account_user_key;
        this.user_key = user_key;
        this.update_time = update_time;
    }

    public static TagUser init(long account_user_key) {
        return new TagUser(account_user_key, "", 0);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {

        Table tableRes = tableEnv.sqlQuery(TableUser.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUser>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUser.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUser>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUser> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUser-proxy-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUser>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUser> value)
                                            throws Exception {
                                        return value.f1.getAccount_user_key();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<Tuple2<Boolean, TableUser>, String>() {
                                    ValueState<TagUser> userVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        userVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<TagUser>(
                                                                        "userVState-proxy",
                                                                        TagUser.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUser> value, Collector<String> out)
                                            throws Exception {
                                        long account_user_key = value.f1.getAccount_user_key();
                                        String user_key = value.f1.getUser_key();
                                        int update_time =
                                                (int) (value.f1.getUpdate_time().getTime() / 1000);

                                        TagUser tmpState = userVState.value();
                                        TagUser curState =
                                                tmpState == null
                                                        ? TagUser.init(account_user_key)
                                                        : tmpState;

                                        if (update_time > curState.getUpdate_time()) {
                                            if (!user_key.equals(curState.getUser_key())) {
                                                curState.user_key = user_key;
                                                curState.update_time = update_time;

                                                JSONObject jsonObject = new JSONObject();
                                                jsonObject.put(
                                                        "account_user_key", account_user_key);
                                                jsonObject.put("user_key", user_key);

                                                userVState.update(curState);
                                                out.collect(jsonObject.toString());
                                            }
                                        }
                                    }
                                });
        return out;
    }

    public long getAccount_user_key() {
        return account_user_key;
    }

    public String getUser_key() {
        return user_key;
    }

    public int getUpdate_time() {
        return update_time;
    }
}
